package org.community.picture.controller;

import entity.CommonResult;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.community.picture.repository.dao.CustomFile;
import org.community.picture.repository.flag.PictureEnum;
import org.community.picture.service.download.DownloadService;
import org.community.picture.service.upload.UploadService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.UUID;

@RestController
@Data
@Slf4j
public class UploadController {

    @Resource
    private UploadService uploadService;

    @Resource
    private DownloadService downloadService;


    //头像上传成功后将头像文件通过路由返回给信息层服务
    @PostMapping(
            value = "/portrait/{userId}",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE
    )
    public ResponseEntity<byte[]> portraitUpload(@PathVariable("userId") Integer  userId, MultipartFile file){
        log.info("portraitUpload开始执行");
        log.info("文件原始名：{}",file.getOriginalFilename());
        boolean result = getUploadService().upload(new CustomFile(userId, PictureEnum.portrait,"",file));
        log.info("文件上传结果:{}",result);
        if(result){
            CustomFile getBufferedImgRequest = new CustomFile(userId,PictureEnum.portrait,"",null);
            return downloadService.getResponseBodyPortrait(getBufferedImgRequest);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentLength(0);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setAccessControlExposeHeaders(Arrays.asList("*"));
        return new ResponseEntity<byte[]>(null,headers ,HttpStatus.EXPECTATION_FAILED);
    }
}
